package com.irishud.hudnavi.udp;

import android.os.ConditionVariable;
import android.util.Log;

import com.irishud.aidl.MsgClient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class MulticastSender extends Thread {
  String Tag = "MulticastSender";
  ConditionVariable lock =new ConditionVariable(false);
  List<ByteBuffer> queue = new ArrayList<>();
  String ip = "224.0.0.1";
  int port=4000;

  public MulticastSender(String ip,int port){
    this.ip = ip;
    this.port = port;
    Log.e(Tag, "multicast sender run:@" + ip +":"+port);
  }

  public void enqueToSend(ByteBuffer buffer){
    queue.add(buffer);
    lock.open();
  }

  @Override
  public void run() {
    InetAddress group= null;
    MulticastSocket ms = null;

    try {
      group = InetAddress.getByName(ip);
      ms = new MulticastSocket(port);
      ms.setTimeToLive(3);
      ms.joinGroup(group);

      while (true) {
        if(queue.size() > 0){
          ByteBuffer byteBuffer = queue.get(0);
          DatagramPacket dp = new DatagramPacket(byteBuffer.array(), byteBuffer.array().length,group,port);
          ms.send(dp);
          queue.remove(0);
          Log.i(Tag,"发送数据报给 "+group+":"+port);
        }else{
          lock.close();
          lock.block();
        }
      }
    }catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ms != null) {
        try {
          ms.leaveGroup(group);
          ms.close();
        }
        catch (IOException e) {}
      }
    }
  }
}

